import { Toast } from 'antd-mobile'
import axios, { AxiosError } from 'axios'
import { getToken, hasToken } from './auth'
import history from './history'
import store from '@/store'
import { logout, saveToken } from '@/store/action/user'
// import { authorizationsPut } from '@/api'
const _axios = axios.create({
  baseURL: 'http://toutiao.itheima.net/v1_0/',
  // baseURL: 'http://geek.itheima.net/v1_0/',
  timeout: 5000
})
_axios.interceptors.request.use(
  config => {
    console.log(config)

    if (hasToken()) {
      config.headers!.Authorization = `Bearer ${getToken().token}`
    }
    return config
  },
  err => {
    Promise.reject(err)
  }
)
_axios.interceptors.response.use(
  res => {
    return res
  },
  async (err: AxiosError) => {
    console.log([err])
    if (!err.response) {
      Toast.show('服务器异常')
      return Promise.reject(err)
    }
    if (!hasToken()) {
      store.dispatch(logout())
      history.push('/login')
      Toast.show({ content: '请重新登录' })

      return Promise.reject(err)
    }
    if (err.response.status === 401) {
      try {
        const resToken = await axios({
          url: 'http://geek.itheima.net/v1_0/authorizations',
          method: 'put',
          headers: {
            Authorization: `Bearer ${getToken().refresh_token}`
          }
        })
        console.log('token', resToken)

        store.dispatch(
          saveToken({
            token: resToken.data.data.token,
            refresh_token: getToken().refresh_token
          })
        )
        return _axios(err.config)
      } catch (error) {
        store.dispatch(logout())
        history.push('/login')
        Toast.show({ content: '请重新登录' })
        return Promise.reject(err)
      }
    }

    Toast.show(err.response?.data.message)
    Promise.reject(err)
  }
)
export default _axios
